﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web.Configuration;

namespace Skynet.WebFoundation.Views.MachineMgm
{
    public class MachineMgmPresenter : Infrastructure.Web.Views.Master.MasterPresenter<IMachineMgmView>
    {
        public override void OnViewInitialized()
        {
            var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            var section = config.GetSectionGroup("system.web").Sections["machineKey"] as System.Web.Configuration.MachineKeySection;
            this.View.validationKey = section.ValidationKey;
            this.View.decryptionKey = section.DecryptionKey;
            this.View.validation = section.Validation.ToString();
            this.View.decryption = section.Decryption;    
        }
        public override void OnViewLoaded()
        {
                  
        }
        public void ProtectSecureSetting()
        {
            var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            var section = config.GetSectionGroup("system.web").Sections["machineKey"] as System.Web.Configuration.MachineKeySection;
            section.ValidationAlgorithm = "SHA1";
            section.ValidationKey=this.getKey(128);
            section.Decryption = "AES";
            section.DecryptionKey = this.getKey(64);
            section.SectionInformation.ForceSave = true;
            config.Save(System.Configuration.ConfigurationSaveMode.Full);            
        }
        private string getKey(int lenght =128)
        {
            byte[] buff = new byte[lenght / 2];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(buff);
            StringBuilder sb = new StringBuilder(lenght);
            for (int i = 0; i < buff.Length; i++)
                sb.Append(string.Format("{0:X2}", buff[i]));
            return sb.ToString();
        }

        public void EncryptConnectionString()
        {
            var config = WebConfigurationManager.OpenWebConfiguration("~");
            var cs = config.GetSection("connectionStrings");
            cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");            
            config.Save(saveMode: System.Configuration.ConfigurationSaveMode.Full);
        }
        public void DecryptConnectionString()
        {
            var config = WebConfigurationManager.OpenWebConfiguration("~");
            var cs = config.GetSection("connectionStrings");
            cs.SectionInformation.UnprotectSection();
            config.Save(saveMode: System.Configuration.ConfigurationSaveMode.Full);
        }

    }
}
